package com.xkw.autocode.base;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xkw.autocode.vo.UserConfigVo;

public class BaseController {
	
	private static Logger logger = LoggerFactory.getLogger(BaseController.class);

	public static final String SESSION_USER_KEY = "SESSION_USER";

	public static final String SESSION_USER_LOGIN_CODE = "SESSION_LOGIN_CODE";

	protected void setSessionUser(HttpServletRequest request, UserConfigVo userConfigVo) {
		request.getSession().setAttribute(SESSION_USER_KEY, userConfigVo);
	}

	protected UserConfigVo getSessionUser(HttpServletRequest request) {
		return (UserConfigVo) request.getSession().getAttribute(SESSION_USER_KEY);
	}

	protected Long getSessionUserId(HttpServletRequest request) {
		UserConfigVo user = this.getSessionUser(request);
		if (user != null) {
			return user.getId();
		} else {
			return null;
		}
	}

	protected void removeSessionUser(HttpServletRequest request) {
		request.getSession().removeAttribute(SESSION_USER_KEY);
	}

	protected String getSessionUserName(HttpServletRequest request) {
		UserConfigVo user = this.getSessionUser(request);
		if (user != null) {
			return user.getNikeName();
		} else {
			return null;
		}
	}

	protected void sendRedirect(HttpServletResponse response, String url) {
		// 跳转到登录页面
		response.setStatus(302);// 或者303,兼容http1.1
		response.setHeader("location", url);
	}

	protected void setSessionLoginCode(HttpServletRequest request, String loginCode) {
		request.getSession().setAttribute(SESSION_USER_LOGIN_CODE, loginCode);
	}

	protected boolean checkSessionLoginCode(HttpServletRequest request, String loginCode) {

		Object sessionLoginCode = request.getSession().getAttribute(SESSION_USER_LOGIN_CODE);
		if (sessionLoginCode == null || !loginCode.equals(sessionLoginCode)) {
			return false;
		}

		request.getSession().removeAttribute(SESSION_USER_LOGIN_CODE);
		return true;
	}

	/**
	 * 导出操作
	 * 
	 * @param filePath
	 * @param response
	 * @param fileName
	 * @param fileType
	 * @param isDelete
	 * @return
	 * @throws IOException 
	 * @throws Exception
	 */
	protected boolean downLoadFile(String filePath, HttpServletResponse response, String fileName,
			String fileType, boolean isDelete) throws IOException{
		File file = new File(filePath);// 根据文件路径获得File文件
		if (!file.exists()) {
			return false;
		}
		// 设置文件类型(这样设置就不止是下Excel文件了，一举多得)
		if ("pdf".equals(fileType)) {
			response.setContentType("application/pdf;charset=GBK");
		} else if ("xls".equals(fileType)) {
			response.setContentType("application/msexcel;charset=GBK");
		} else if ("doc".equals(fileType)) {
			response.setContentType("application/msword;charset=GBK");
		}
		// 文件名
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1"));
		response.setContentLength((int) file.length());
		byte[] buffer = new byte[4096];// 缓冲区
		try (BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream());
				BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));) {

			int n = -1;
			// 遍历，开始下载
			while ((n = input.read(buffer, 0, 4096)) > -1) {
				output.write(buffer, 0, n);
			}
			output.flush(); // 不可少
			response.flushBuffer();// 不可少
		} catch (Exception e) {
			logger.error("",e);
		} finally {
			if (isDelete) {
				Files.delete(file.toPath());
			}
		}
		return true;
	}
}
